<template>
    <div class="validate-input-container pb-3">
        <input class="form-control"
        :class="{'is-invalid': inputRef.error}"
        @blur="validateInput"
        v-model="inputRef.val"
        v-bind="$attrs">
        <span v-if="inputRef.error" class="invalid-feedback">{{inputRef.message}}</span>
    </div>    
</template>
<script lang="ts">
import {defineComponent, reactive, PropType, computed, onMounted} from 'vue'
import {emitter} from "./ValidateForm.vue"
interface RuleProp {
    type: "required" | "email";
    message: string;
}
export type RulesProp = RuleProp[];

const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;


export default defineComponent({
    name: "ValidateInput",
    inheritAttrs: false,
    props: {
        rules: Array as PropType<RulesProp>,
        modelValue: String,
    },
    setup(props, context) {
        const inputRef = reactive({
            val: computed({
                get: () => props.modelValue || "",
                set: val => {
                    context.emit('update:modelValue', val)
                }
            }),
            error: false,
            message: "",
        })
        const validateInput = () => {
            if(props.rules){
                const allPassed = props.rules.every(rule => {
                    let passed = true
                    inputRef.message = rule.message
                    switch(rule.type) {
                        case "required":
                            passed = (inputRef.val.trim() !== '');
                            break;
                        case "email":
                            passed = reg.test(inputRef.val);
                            break;
                        default:
                            break;
                    }
                    return passed;
                })
                inputRef.error = !allPassed;
                return allPassed;
            }
        }
        onMounted(() => {
            emitter.emit("form-item-created", validateInput);
        })
        return {
            inputRef,
            validateInput,
        }
    }
})
</script>